package easymall.service;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import easymall.dao.ProductsDao;
import easymall.po.Category;
import easymall.po.Products;
import easymall.pojo.MyPage;
import easymall.pojo.MyProducts;

@Service("productsService")
public class ProductsServiceImpl implements ProductsService {

	@Autowired
	private ProductsDao productsDao;

	@Override
	public List<Category> allcategorys() {
		List<Category> categorys = productsDao.allcategorys();
		return categorys;
	}

	@Override
	public List<Products> prodlist(Map<String, Object> map) {
		List<Products> products = productsDao.prodlist(map);
		return products;
	}

	@Override
	public Products oneProduct(String pid) {
		return productsDao.oneProduct(pid);
	}

	@Override
	public List<Products> proclass(Integer category) {
		return productsDao.proclass(category);
	}

	@Override
	public String save(MyProducts myproducts, HttpServletRequest request) {
		// 1.判断后缀是否合法
		// 获取图名称，后缀名称
		String originName = myproducts.getImgurl().getOriginalFilename();

		// 截取后缀substring split(".jpg" ".png")
		String extName = originName.substring(originName.lastIndexOf("."));

		if (!(extName.equalsIgnoreCase(".jpg") || extName.equalsIgnoreCase(".png")
				|| extName.equalsIgnoreCase(".gif"))) {
			// 图片后缀不合法
			return "图片后缀不合法";
		}

		// 判断木马（java的类判断是否是图片属性，也可引入第三方jar包判断
		try {
			BufferedImage bufImage = ImageIO.read(myproducts.getImgurl().getInputStream());
			bufImage.getHeight();
			bufImage.getWidth();
		} catch (Exception e) {
			return "该文件不是图片！";
		}

		// 2.创建upload开始的一个路径
		// 生成多级路径
		String imgurl = "";
		// /a/2/e/a/2/3/j/p
		for (int i = 0; i < 8; i++) {
			imgurl += "/" + Integer.toHexString(new Random().nextInt(16));
		}
		String realpath = request.getServletContext().getRealPath("/");
		realpath += "/upload";
		System.out.println(realpath + imgurl);
		File file = new File(realpath + imgurl, originName);
		if (!file.exists()) {
			file.mkdirs();
		}
		// 上传文件
		try {
			myproducts.getImgurl().transferTo(file);
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 拼接图片存入数据库的路径
		imgurl = "/upload" + imgurl + "/" + originName;
		String id = UUID.randomUUID().toString();
		Products products = new Products();
		products.setId(id);
		products.setName(myproducts.getName());
		products.setCategory(myproducts.getCategory());
		products.setPrice(myproducts.getPrice());
		products.setPnum(myproducts.getPnum());
		products.setImgurl(imgurl);
		products.setDescription(myproducts.getDescription());
		if (productsDao.findByImgurl(products.getImgurl()) == null) {
			productsDao.save(products);
		} else {
			String fname = imgurl.substring(0, imgurl.lastIndexOf("."));
			imgurl = fname + System.currentTimeMillis() + extName;
			products.setImgurl(imgurl);
			System.out.println(products.getImgurl());
			productsDao.save(products);
		}
		return "商品添加成功";
	}

	/********************** 分页相关 **************************/
	@Override
	public List<Category> getCategorysByPage(Integer page) {
		MyPage mypage = new MyPage(page);
		return productsDao.getCategorysByPage(mypage);
	}

	@Override
	public int getTotalPage() {
		return (productsDao.getCategorysCount() - 1) / MyPage.size + 1;
	}

	@Override
	public List<Products> getProductsByPage(Integer page) {
		MyPage mypage = new MyPage(page);
		return productsDao.getProductsByPage(mypage);
	}

	@Override
	public int getTotalPageByProducts() {
		return (productsDao.getProductsCount() - 1) / MyPage.size + 1;
	}

	/******************* 类别相关 *****************/
	@Override
	public int updateCategory(Category category) {
		return productsDao.updateCategory(category);
	}

	// 存在返回-1 保存失败返回0 成功返回1
	@Override
	public int saveCategory(String name) {
		int num = productsDao.checkCategorysExist(name);
		if (num > 0) { // 已经存在
			return -1;
		} else {
			return productsDao.saveCategory(name);
		}
	}

	@Override
	public int delCategory(Integer id) {
		return productsDao.delCategory(id);
	}

	@Override
	public String updatePruduct(MyProducts myproducts, HttpServletRequest request, String id) {
		Products products = new Products();
		
		//用户有上传图片才读取图片
		if(myproducts.getImgurl().getSize()!=0) {
			String imgurl = checkimg(myproducts.getImgurl(),request);
			if(imgurl.equals("0")) {
				return "图片后缀不合法！";
			}else if(imgurl.equals("1")) {
				return "该文件不是图片!";
			}
			String originName = myproducts.getImgurl().getOriginalFilename();
			String extName = originName.substring(originName.lastIndexOf("."));
			products.setImgurl(imgurl);
			if (productsDao.findByImgurl(products.getImgurl()) != null) {
				String fname = imgurl.substring(0, imgurl.lastIndexOf("."));
				imgurl = fname + System.currentTimeMillis() + extName;
				products.setImgurl(imgurl);
				System.out.println(products.getImgurl());
				
			}
		}
		
		products.setId(id);
		products.setName(myproducts.getName());
		products.setCategory(myproducts.getCategory());
		products.setPrice(myproducts.getPrice());
		products.setPnum(myproducts.getPnum());
		products.setDescription(myproducts.getDescription());
		if(productsDao.updatePruduct(products)==1) {
			return "更新成功";
		}else {
			return "数据库错误";
		}
	}

	@Override
	public int delProduct(String id) {
		return productsDao.delProduct(id);
	}

	// 检查图片是否合法
	// "图片后缀不合法"
	// "该文件不是图片！"
	// imgurl
	public String checkimg(MultipartFile img,HttpServletRequest request) {
		// 1.判断后缀是否合法
		// 获取图名称，后缀名称
		String originName = img.getOriginalFilename();

		// 截取后缀substring split(".jpg" ".png")
		String extName = originName.substring(originName.lastIndexOf("."));

		if (!(extName.equalsIgnoreCase(".jpg") || extName.equalsIgnoreCase(".png")
				|| extName.equalsIgnoreCase(".gif"))) {
			// 图片后缀不合法
			return "0";
		}

		// 判断木马（java的类判断是否是图片属性，也可引入第三方jar包判断
		try {
			BufferedImage bufImage = ImageIO.read(img.getInputStream());
			bufImage.getHeight();
			bufImage.getWidth();
		} catch (Exception e) {
			return "1";
		}

		// 2.创建upload开始的一个路径
		// 生成多级路径
		String imgurl = "";
		// /a/2/e/a/2/3/j/p
		for (int i = 0; i < 8; i++) {
			imgurl += "/" + Integer.toHexString(new Random().nextInt(16));
		}
		String realpath = request.getServletContext().getRealPath("/");
		realpath += "/upload";
		System.out.println(realpath + imgurl);
		File file = new File(realpath + imgurl, originName);
		if (!file.exists()) {
			file.mkdirs();
		}
		// 上传文件
		try {
			img.transferTo(file);
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 拼接图片存入数据库的路径
		imgurl = "/upload" + imgurl + "/" + originName;
		return imgurl;
	}

}
